package com.example.eurekacustomer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zyb
 * @Date: 2018/11/3 16:13
 * @Description: Hystrix断路器
 */
@Service
public class HystrixService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "testFallback")//断路器,指定接口失败时的回调方法
    public String getUserInfoByMap(String name, String password) {

        try {
            //断路器有个默认的超时时间,2秒,超过就会触发回调方法
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("name", name);
        map.put("passwd", password);
        //map形式的传参访问,需要确保map中的key和路径中指定的name一致
        String url = "http://eureka-client/getUserInfo?name={name}&password={passwd}";
        return restTemplate.getForEntity(url, String.class, map).getBody();
    }

    //特别注意,此回调方法需要和原来方法入参保持一致
    private String testFallback(String name, String password) {
        return "request error,param : name = " + name + ", password = " + password;
    }
}
